<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTool>
        <template #before>
          <span>总共{{ total }}数据</span>
        </template>
        <template #after>
          <el-button size="mini" type="primary" @click="$router.push('/import')">导入</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="exportExcel"
          >导出
          </el-button>
          <el-button size="mini" type="warning " @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTool>

      <el-table
        v-loading="loading"
        :data="list"
        border
      >
        <el-table-column label="序号" prop="id" type="index" width="50" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像" prop="staffPhoto">
          <template #default="{row}">
            <el-avatar :size="80" :src="row.staffPhoto" @click.native="handlerFn(row.staffPhoto)">
              <template #default>
                <img alt="" src="@/assets/common/bigUserHeader.png">
              </template>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column :formatter="formatter" label="聘用形式" prop="formOfEmployment" />
        <el-table-column label="部门名称" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry">
          <template #default="{ row }">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" prop="formOfEmployment">
          <el-switch
            :value="false "
            active-color="black"
            inactive-color="#ff4949"
          />
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{row}">
            <el-row justify="space-between" type="flex">
              <el-link type="primary" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-link>
              <el-link type="primary">转正</el-link>
              <el-link type="primary">调岗</el-link>
              <el-link type="primary">离职</el-link>
              <el-link type="primary " @click="handlecontrolRoleShow(row.id)">角色</el-link>
              <el-link v-auth="'DELETE_EMP'" type="primary" @click="delEmployFn(row.id)">删除
              </el-link>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-row
        align="middle"
        justify="center"
        style="height: 80px;"
        type="flex"
      >
        <el-pagination
          :current-page="page.page"
          :page-size="page.size"
          :total="total"
          background
          layout="total,prev,pager,next"
          @current-change="pageChangeFn"
        />
      </el-row>
    </div>
    <EmployEe :show-dialog.sync="showDialog" />
    <el-dialog :visible.sync="dialogVisible">
      <canvas ref="qrCodeUrl" />
    </el-dialog>
    <RoleDialog ref="roleCurrent" :role-id="roleId" :role-show="controlRoleShow" @closeROlesDialog="closeROlesDialog" />
  </div>
</template>

<script>
import QRCode from 'qrcode'
// 引入映射表
import Employ from '@/api/constant/employees'
import { delEmploy, getEmployeesList } from '@/api/settings'
import EmployEe from '@/views/employees/components/add-employee'
import { formatDate } from '@/api/filters/index'
import RoleDialog from '@/views/employees/components/RoleDialog.vue'
// mixin 混入
import mini from '@/checkpermission/checkpermission'

export default {
  components: {
    EmployEe, RoleDialog
  },
  mixins: [mini],
  data() {
    return {
      roleId: null,
      controlRoleShow: false, // 角色控制弹层 权限分配
      dialogVisible: false,
      page: {
        page: 1,
        size: 10
      },
      list: [],
      total: 0,
      loading: false,
      showDialog: false
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    closeROlesDialog() {
      this.controlRoleShow = false
    },
    handlecontrolRoleShow(id) {
      this.roleId = id
      this.$refs.roleCurrent.getCurrentId(id)
      this.controlRoleShow = true
    },
    handlerFn(info) {
      if (!info) return this.$message.error('当前用户没有头像数据')
      this.dialogVisible = true
      this.$nextTick(() => {
        QRCode.toCanvas(this.$refs.qrCodeUrl, info)
      })
    },
    async exportExcel() {
      const [{ export_json_to_excel }, { rows }] = await Promise.all([import('@/vendors/exportExcel.js'), getEmployeesList({
        page: 1,
        size: this.total
      })])
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const data = this.formatjson(headers, rows)
      export_json_to_excel({
        header: Object.keys(headers), // 表头 必填
        data, // 具体数据 必填
        filename: 'excel-list', // 非必填
        autoWidth: true, // 非必填
        bookType: 'xlsx' // 非必填
      })
    },
    formatjson(headers, rows) {
      const arr = rows.map(item => {
        return Object.keys(headers).map(key => {
          if (['timeOfEntry', 'correctionTime'].includes(headers[key])) {
            return formatDate(item[headers[key]])
          }
          if (headers[key] === 'formOfEmployment') {
            const current = Employ.hireType.find(emItem => {
              return emItem.id === +item[headers[key]]
            })
            return current?.value || '未知'
          }
          return item[headers[key]]
        })
      })
      return arr
    },
    async delEmployFn(id) {
      try {
        await this.$confirm('确定删除吗')
        await delEmploy(id)
        await this.$message.success('删除成功')
        this.getEmployees()
      } catch {
        this.$message.error('已取消')
      }
    },
    async getEmployees() {
      this.loading = true
      const res = await getEmployeesList(this.page)
      this.list = res.rows
      this.total = res.total
      this.loading = false
    },
    pageChangeFn(page) {
      this.page.page = page
      this.getEmployees()
    },
    formatter(row, column, cellValue, index) {
      const current = Employ.hireType.find((item) => item.id === Number(cellValue))
      return current?.value || '未知'
    }

  }

}
</script>

